package org.xfy.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.xfy.base.myannotate.PreAuthorize;
import org.xfy.base.util.JwtUtils;
import org.xfy.base.util.Payload;
import org.xfy.org.domain.LoginData;
import org.xfy.org.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取前端的token
        String token = request.getHeader("token");
        try {
            Payload<LoginData> payload = JwtUtils.getdecode(token);
            LoginData loginData = payload.getLoginData();
            //拿到权限
            List<String> permissions = loginData.getPermissions();
            HandlerMethod handlerMethod=(HandlerMethod)handler;
            PreAuthorize annotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            if(annotation==null){
                return true;
            }else {
                String sn = annotation.sn();
                //contains方法 如果里面包含sn就为true 不包含为false
                return permissions.contains(sn);
            }

        } catch (Exception e) {
            //跳转到登录页面 - 后端跳不了，因为后端项目没有页面 - 放在前端跳转
            //告诉浏览器我要给你响应一个json数据，编码集为utf-8
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
    }
}
